package com.gexin.weixin.uitls;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.LogKit;
import com.jfinal.weixin.sdk.api.AccessTokenApi;
import com.jfinal.weixin.sdk.api.ApiConfig;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.kit.ParaMap;
import com.jfinal.weixin.sdk.utils.HttpUtils;

public class WxTools {
	
	private static String getUserInfo = "https://api.weixin.qq.com/cgi-bin/user/info";
	private static String sendApiUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=";
	
	
	/**
	 * 支付成功返回的信息
	 * @param return_code SUCCESS 成功  FAIL  失败
	 * @param return_msg 默认传空的
	 * @return
	 */
	public static String wxPayResponse(String return_code, String return_msg) {
		return "<xml><return_code><![CDATA[" + return_code
				+ "]]></return_code><return_msg><![CDATA[" + return_msg
				+ "]]></return_msg></xml>";
	}
	/**
	 * 获取当前的微信的AccessToken
	 * @return
	 */
	public static String getAccessToken(){
		ApiConfig ac = new ApiConfig();
		ac.setAppId(WxConfig.AppID);
		ac.setAppSecret(WxConfig.AppSecret);
		ApiConfigKit.setThreadLocalAppId(WxConfig.Api_Config.getAppId());
		return AccessTokenApi.getAccessToken().getAccessToken();
	}
	
	
	/**
	 * 重写获取用户信息
	 * @param openId
	 * @return
	 */
	public static JSONObject getUserInfo(String openId) {
		ParaMap pm = ParaMap
				.create("access_token", AccessTokenApi.getAccessTokenStr())
				.put("openid", openId).put("lang", "zh_CN");
		String obj = HttpKit.get(getUserInfo, pm.getData());
		return JSONObject.parseObject(obj);
	}
	
	/**
	 * 推送模板消息
	 * @param token
	 * @param json
	 * @return
	 */
	public static boolean sendTemplate(String token ,String jsonStr){
		//String jsonResult = HttpUtils.post(sendApiUrl+ AccessTokenApi.getAccessToken().getAccessToken(), jsonStr);
		String jsonResult = HttpUtils.post(sendApiUrl+ token, jsonStr);
		ApiResult result = new ApiResult(jsonResult);
		if(result.getInt("errcode")==0 ){
			return true;
		}else{
			LogKit.info("推送消息失败："+jsonResult);
			return false;
		}

	}
}
